import Dialog from '../../vant-weapp/dialog/dialog';
import Toast from '../../vant-weapp/toast/toast';
import fw from '../../core/framework.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    type: 'create',
    person: {
      name: '',
      age: '',
      url: '',
      sex: 1,
      remark: ''
    },
    sexChoose: {},
    sexShow: false,
    sexActions: [
      {
        name: '男',
        value: 1
      }, {
        name: '女',
        value: 2
      }
    ],
    fileList: []
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var type = options.type;
    this.setData({
      type: type
    });
    wx.setNavigationBarTitle({
      title: this.data.type == 'create' ? '添加被看护人' : '编辑被看护人'
    });
    if (type == 'edit') {
      console.log('options', options)
      let person = JSON.parse(options.person);
      this.setData({
        person: person,
        sexChoose: this.data.sexActions[person.sex-1],
        fileList:person.url ? [{url:fw.url.gen(person.url)}]:[]
      })
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },
  setValue(event) {
    var _value = event.detail;
    var propName = fw.getTargetData(event, 'name');
    this.setData({
      ['person.' + propName]: _value
    });
  },
  cancel() {
    fw.url.back();
  },
  save: function () {
    let self = this;
    var ajaxData = self.data.person;
    if (!ajaxData.name) {
      Toast.fail('姓名不能为空')
      return false;
    }
    if (this.data.type == 'create') {
      fw.ajax('face/create', ajaxData).then(res => {
        if (res.code == 0) {
          Toast.success('添加被看护人成功');
          self.cancel();
        } else {
          Toast.fail(res.msg);
        }
      })
    } else {
      fw.ajax('face/update', ajaxData).then(res => {
        if (res.code == 0) {
          Toast.success('更新被看护人成功');
          self.cancel();
        } else {
          Toast.fail(res.msg);
        }
      })
    }
  },
  openSex() {
    this.setData({
      sexShow: true
    })
  },
  closeSexShow() {
    this.setData({
      sexShow: false
    })
  },
  chooseSex(e) {
    console.log(e.detail);
    this.setData({
      sexChoose: e.detail,
      ['person.sex']:e.detail.value
    })
    this.setData({
      sexShow: false
    })
  },
  deleteImg(event) {
    console.log('delete', event);
    this.setData({
      'fileList': [],
      ['person.url']: ''
    });
  },
  upload(event) {
    var self = this;
    const { file } = event.detail;
    // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
    wx.uploadFile({
      url: fw.config.PARAM.UPLOAD_BASE_URL, // 仅为示例，非真实的接口地址
      filePath: file.url,
      name: 'userImg',
      formData: { token: fw.user.get().token },
      success(res) {
        // 上传完成需要更新 fileList
        const { fileList = [] } = self.data;
        fileList.push({ ...file, url: res.data });
        self.setData({
          fileList: fileList,
          ['person.url']: (res.data||{}).data
        });
      },
    });
  }
})